package com.acme.test;

import static org.junit.Assert.*;

import static org.hamcrest.core.Is.is;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.acme.StartServer;
import com.acme.domain.MarketData;
import com.acme.domain.Operationtype;
import com.acme.domain.Order;
import com.acme.domain.Orderstatus;
import com.acme.domain.Responses;
import com.acme.domain.StartClient;
import com.acme.domain.Writer;
import com.acme.domain.request.CancelOrderRequest;
import com.acme.domain.request.PlaceOrderRequest;
import com.acme.domain.request.SubscribeMarketDataRequest;

public class CancelTestCase {

	@BeforeClass
	public static void setUpBeforeClass(){
		StartServer.start(2013);
	}
	
	@Before 
	public void setUp() throws Exception {
		StartClient.start("127.0.0.1", 2013, "Oleg");
	}
	
	@Test
	public void shouldCancelOrderWhenReqested() throws InterruptedException{
		Order order = new Order("Oleg", Operationtype.BUY, "TNK", 10, 10, 1);
		Writer.writeRequest(new PlaceOrderRequest(order));
		Writer.writeRequest(new CancelOrderRequest(order));
		
		synchronized (Responses.get()) {
			if (Responses.get().size()<3){
				Responses.get().wait();
			}
			assertThat(Responses.get().get(1).getOrder().getStatus(),is(Orderstatus.CANCELLED));
		}
		Writer.writeRequest(new SubscribeMarketDataRequest("TNK", "Oleg"));
		assertTrue(!MarketData.get().contains(order));
		
	}
	
	@After
	public void tearDown() throws Exception{
		Responses.get().clear();
		StartClient.shutdown();
	}
	
	@AfterClass
	public static void tearDownAfterClass() throws Exception{
		StartServer.shutdown();
	}
}
